package com.scalar.chiptrack.adaptor.spil;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;

import java.io.InputStreamReader;
import java.io.BufferedInputStream;
import java.net.URL;

import HTTPClient.HTTPConnection;
import HTTPClient.HTTPResponse;
import HTTPClient.NVPair;
import HTTPClient.CookieModule;

/**
 * Created by IntelliJ IDEA.
 * User: Sudhakar
 * Date: May 07, 2007
 * Time: 5:11:33 PM
 *
 */
public class SPILAdaptor extends JobHandler implements AdaptorConstants
{
    private static final String HOST                    = "web66.spilglobal.com";
    private static final String HOST1                   = "web7.spilglobal.com";
    private static final int PORT                       = 80;
    private static final int PORT1                      = 443;
    private static final String GET_PRODUCTION_INFO     = "/CIP/Portal/Production%20Information/";
    //private static final String GET_WIP_REPORT_DETAIL   ="/WIP/StaticCheck.asp?url=http%3A%2F%2Fweb6%2Espil%2Ecom%2Etw%2Fwarehouse%2FSZ%2FGSTL%28LS%29%2FSFCB007%5FDAY%5F00%2ECSV&dir=%5C%5Cweb6%5Cwarehouse%5CSZ%5CGSTL%28LS%29%5CSFCB007%5FDAY%5F00%2ECSV";
    private static final String GET_POST_DOWN_LOAD_LINK ="/WIP/StaticResult.asp";
    private static final String GET_DOWN_LOAD_LINK      ="/WIP/download.asp";
    public static final String FILE_NAME_WIP_STATUS     = "SPIL_WIP_STATUS";
    public static final String ADAPTOR_NAME             = "SPIL_WIP";
    private static final String PROTOCOL_SCHEME_HTTPS   = "https";

    // CLASS VARIABLES
    private HTTPConnection m_connection     = null;
    private HTTPConnection m_connection1    = null;
    private HTTPResponse rsp                = null;
    private Logger m_adaptorLogger          = null;
    private String m_dataOutputDir          = null;
    private String m_username               = null;
    private String m_password               = null;
    private String customerName             = null;
    private static URL s_dummyUrl           = null;
    private int    m_adaptor_id     = -1;
    public SPILAdaptor() throws ScalarException
    {

        if (s_dummyUrl == null)
        {
            try
            {
                s_dummyUrl = new URL("http://" + HOST );
            }
            catch (Exception ignore) {
            }
        }

        try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation(VENDOR_NAME_SPIL, WIP_TYPE_ASSEMBLY);

            m_username = vendorAdaptor.getUserId();
            m_password = vendorAdaptor.getPassWord();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory();
            customerName = vendorAdaptor.getCustomerId();
            
            if (m_dataOutputDir != null)
            {
                if (m_dataOutputDir.endsWith("/") || m_dataOutputDir.endsWith("\\"))
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }
            }
            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
            m_adaptorLogger = AdaptorUtils.getAdaptorLogger( m_dataOutputDir, VENDOR_NAME_SPIL );
            AdaptorUtils.setLogger( m_adaptorLogger );
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading Spil Adaptor Username, Password details from database, Exception: " + se);
            throw se;
        }
        
    }
    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main( String[] args ) throws Exception
    {
        new SPILAdaptor().execute();
    }

    /**
     *
     * @throws Exception
     */
    public void execute() throws Exception
    {
        try
        {
             m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);

            //Print the header details
            AdaptorUtils.printHeader(VENDOR_NAME_SPIL, CONSTANT_ADAPTOR );

            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );
            //login to the Site
            login();

            BufferedInputStream bfReader = null;

            if (rsp != null)
            {
                bfReader = new BufferedInputStream(rsp.getInputStream());
                if (bfReader != null)
                {
                    AdaptorUtils.saveAsBinaryFile(bfReader, m_dataOutputDir, FILE_NAME_WIP_STATUS, FILE_EXTN_XLS, true);
                    if ( m_adaptor_id > 0 )
                    {
                        AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_WIP_STATUS, FILE_EXTN_XLS, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                    }
                    System.out.println("\nDone  ");
                }
                else
                {
                    log("Could not save WIP Status Sheet from Buffer Reader");
                    throw new ScalarException("Could not save WIP Status Sheet from Buffer Reader");
                }
            }
            else
            {
                log("Could not create response object of WIP Status Sheet");
                throw new ScalarException("Could not create response object of WIP Status Sheet");
            }
        }
        catch (Exception e )
        {
            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger);
            AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id );
            System.out.println("Exception while trying to connect and read data from "+ HOST +" site: " + e);
            e.printStackTrace();
            throw e;
        }
    }
    /**
     *
     * @throws Exception
     */
    private void login() throws Exception
    {
        byte[] data = new byte[1024];
        try
        {

            NVPair defaultHeaders[] = new NVPair[10];
            defaultHeaders[0] = new NVPair( "Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*" );
            defaultHeaders[1] = new NVPair( "Accept-Language", "en-us" );
            defaultHeaders[2] = new NVPair( "Proxy-Connection", "Keep-Alive" );
            defaultHeaders[3] = new NVPair( "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" );
            defaultHeaders[4] = new NVPair( "Host", HOST );

            m_connection = new HTTPConnection( HOST, PORT );
            m_connection.setDefaultHeaders( defaultHeaders );

            // Accept all cookies
            CookieModule.setCookiePolicyHandler( null );
            HTTPConnection.addDefaultModule( CookieModule.class, -1 );
            log( "Trying to login................." );
            System.out.println( "Trying to login..............." );

            m_connection.addBasicAuthorization( HOST, m_username, m_password );
            rsp = m_connection.Get( GET_PRODUCTION_INFO );

            System.out.println("successfully logged in\n");
            log("successfully logged in\n");

            // This Connection gets the web7.spil.com.tw, as it is changeing from WEB6 to WEB7
            getAnotherHOSTConnection(  );

        }
        catch ( Exception se )
        {
            throw new ScalarException( "\n\n***** ERROR!! ERROR!! ERROR!! Failed to Connect SPIL Site" + se );
        }

    }

    /**
     *
     * @return
     * @throws Exception
     */
    private HTTPResponse getAnotherHOSTConnection() throws Exception
    {

        byte[] data = new byte[1024];
        try
        {
            System.out.print("\t\nProcessing for Wip Daily Report........... ");
            log("\n Processing for Wip Daily Report.... ");

            NVPair defaultHeader[] = new NVPair[8];
            defaultHeader[0] = new NVPair("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*");
            defaultHeader[1] = new NVPair("Referer", "http://" + HOST + GET_PRODUCTION_INFO);
            defaultHeader[2] = new NVPair("Accept-Language", "en-us");
            defaultHeader[3] = new NVPair("Proxy-Connection", "Keep-Alive");
            defaultHeader[4] = new NVPair("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
            defaultHeader[5] = new NVPair("Host", HOST1);

            //Get the Connection using another Host
            m_connection1 = new HTTPConnection(PROTOCOL_SCHEME_HTTPS, HOST1, PORT1);
            m_connection1.setDefaultHeaders(defaultHeader);

            CookieModule.setCookiePolicyHandler(null);
            HTTPConnection.addDefaultModule(CookieModule.class, -1);

            rsp = m_connection1.Get("/WIP/StaticCheck.asp?url=http%3A%2F%2Fweb6%2Espil%2Ecom%2Etw%2Fwarehouse%2F"+ customerName +"%2FSFCB007%5FDAY%5F00%2ECSV&dir=%5C%5Cweb6%5Cwarehouse%5C"+customerName +"%5CSFCB007%5FDAY%5F00%2ECSV");
            log("rsp.getEffectiveURI() = " + rsp.getEffectiveURI());
            rsp = m_connection1.Get(GET_POST_DOWN_LOAD_LINK);

            System.out.print("\t\nDownloading Wip Daily Report........... ");
            log("\n Downloading Wip Daily Report.... ");

            SPILHtmlParser parser = new SPILHtmlParser();
            parser.parse(new InputStreamReader(rsp.getInputStream()));
            NVPair formData[] = new NVPair[2];
            formData[0] = new NVPair("button1", "SAVE FILE");
            formData[1] = new NVPair("filename", parser.getDownLoadFileName());
            rsp = m_connection1.Get(GET_DOWN_LOAD_LINK, formData);

        }
        catch (Exception e)
        {
            throw new ScalarException("\n\n***** ERROR!! ERROR!! ERROR!! While Connectiong & downloading WIP From SPIL Site" + e);
        }
        return rsp;

    }

    public void readData( HTTPResponse rsp, int debug ) throws Exception
    {

        byte[] data = new byte[2048];
        while ( rsp.getInputStream().read( data ) != -1 )
        {
            if ( debug == 0 )
            {
                //System.out.println( new String( data ) );
                log( new String( data) );
            }
        }
    }

    private void log( String message )
    {
        if ( message == null ) return;

        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }

}
